<template>
  <div class="outbox">
    <h2>
      学校公告
      <el-button type="primary" icon="el-icon-plus" @click="showAddDialog"
        >添加</el-button
      >
    </h2>
    <el-table
      @row-click="handleRowClick"
      :data="
        notices.filter(
          (data) =>
            !search ||
            data.title.toLowerCase().includes(search.toLowerCase()) ||
            data.sender.toLowerCase().includes(search.toLowerCase())
        )
      "
      style="width: 100%"
    >
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column label="日期" prop="date" sortable> </el-table-column>
      <el-table-column label="标题" prop="title"> </el-table-column>
      <el-table-column label="发送方" prop="sender"> </el-table-column>
      <el-table-column align="right">
        <template slot="header" slot-scope="scope">
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入标题或发送方搜索"
          />
        </template>
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click.stop="handleEdit(scope.$index, scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click.stop="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="tablePage.pageNum"
        :page-size="tablePage.pageSize"
        :page-sizes="pageSizes"
        :total="tablePage.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div> -->
    <!-- 显示具体信息的弹出窗口 -->
    <el-dialog
      :visible.sync="detailDialogVisible"
      title="详细信息"
      :close-on-click-modal="false"
      width="50%"
    >
      <div style="white-space: pre-wrap">
        <p><strong>日期:</strong> {{ selectedNotice.date }}</p>
        <p><strong>标题:</strong> {{ selectedNotice.title }}</p>
        <p><strong>发送方:</strong> {{ selectedNotice.sender }}</p>
        <p><strong>内容:</strong> {{ selectedNotice.content }}</p>
      </div>
    </el-dialog>

    <!-- 编辑表单的弹出窗口 -->
    <el-dialog
      :visible.sync="editDialogVisible"
      :title="isAdd ? '添加信息' : '修改信息'"
      :close-on-click-modal="false"
      width="70%"
    >
      <el-form
        ref="editForm"
        :model="selectedNotice"
        label-width="60px"
        :rules="rules"
      >
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="selectedNotice.date"
            type="date"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="selectedNotice.title"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="发送方">
          <el-input
            v-model="selectedNotice.sender"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            v-model="selectedNotice.content"
            maxlength="5000"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button @click="saveEdit" type="primary">保存</el-button>
        <!-- <el-button v-show="!isAdd" type="primary" @click="saveEditedNotice"
          >修改</el-button
        >
        <el-button v-show="isAdd" type="primary" @click="addNotice"
          >添加</el-button
        > -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.fetchNotices();
    // this.fetchData();
  },
  data() {
    return {
      isAdd: true,
      detailDialogVisible: false,
      editDialogVisible: false,
      selectedNotice: {}, // 保存选中的公告信息
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 10, // 每页多少条
        total: 0, // 总记录数
      },
      pageSizes: [5, 10, 20, 30],
      notices: [],
      search: "",
      rules: {
        date: [
          { required: true, message: "日期不能为空", trigger: "blur" }, // 触发校验的时机是失去焦点时
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
          { max: 50, message: "标题不能超过50个字符", trigger: "blur" },
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" },
          { max: 5000, message: "内容不能超过5000个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    saveEdit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // 校验通过，执行保存或添加操作
          if (this.isAdd) {
            // 添加公告
            this.addNotice();
          } else {
            // 编辑公告
            this.saveEditedNotice();
          }
        } else {
          // 校验不通过，不执行保存或添加操作
          this.$message.error("表单校验不通过，请检查输入！");
        }
      });
    },
    fetchData() {
      const { pageNum, pageSize } = this.tablePage;
      // 发送分页请求到后端
      // 你可以使用 axios 或其他 HTTP 请求库
      // 在请求参数中包括页码和每页条数
      // 例如，使用 axios 发送 GET 请求：
      this.$http
        .get(`/notifications/page?pageNum=${pageNum}&pageSize=${pageSize}`)
        .then((response) => {
          // 处理后端返回的分页数据
          const { records, total } = response.data;
          this.notices = records.map((notice) => ({
            id: notice.notiId,
            title: notice.notiTitle,
            date: this.formatDate(new Date(notice.notiTimestamp)), // 注意这里可能需要格式化日期
            content: notice.notiContent,
            sender: notice.notiSender,
          })); // 更新部门数据
          this.tablePage.total = total; // 更新总记录数
        })
        .catch((error) => {
          console.error("Error fetching notifications:", error);
        });
    },
    // 打开添加公告的弹出窗口
    showAddDialog() {
      this.isAdd = true;
      // 初始化选中的公告为空
      this.selectedNotice = {
        date: "",
        title: "",
        sender: "",
        content: "",
      };
      this.editDialogVisible = true; // 打开编辑表单
    },
    handleRowClick(row, column, event) {
      // 阻止事件冒泡
      event.stopPropagation();
      this.handleDetail(row);
      // 其他处理逻辑
    },
    // 添加公告
    addNotice() {
      // 创建一个新的公告对象，将其发送到服务器
      const newNotice = {
        notiTimestamp: this.selectedNotice.date,
        notiTitle: this.selectedNotice.title,
        notiSender: this.selectedNotice.sender,
        notiContent: this.selectedNotice.content,
      };

      this.$http
        .post("/notifications/add", newNotice)
        .then((response) => {
          // 添加成功后刷新数据
          this.fetchNotices();
          // this.fetchData();
          this.$message.success("公告添加成功");
          this.editDialogVisible = false; // 关闭编辑弹窗
        })
        .catch((error) => {
          console.error("Error adding notice:", error);
          this.$message.error("添加公告时出错");
        });
    },
    // 编辑公告
    saveEditedNotice() {
      // 将编辑后的公告对象发送到服务器
      let date = new Date(this.selectedNotice.date);
      const changedNotice = {
        notiId: this.selectedNotice.id,
        notiTitle: this.selectedNotice.title,
        notiTimestamp: date.toISOString(),
        notiContent: this.selectedNotice.content,
        notiSender: this.selectedNotice.sender,
      };
      this.$http
        .put("/notifications/update", changedNotice)
        .then((response) => {
          // 编辑成功后刷新数据
          this.fetchNotices();
          // this.fetchData();
          this.$message.success("公告编辑成功");
          this.editDialogVisible = false; // 关闭编辑弹窗
        })
        .catch((error) => {
          console.error("Error editing notice:", error);
          this.$message.error("编辑公告时出错");
        });
    },
    // 删除公告
    deleteNotice(id) {
      this.$http
        .delete(`/notifications/delete/${id}`)
        .then((response) => {
          // 删除成功后刷新数据
          this.fetchNotices();
          // this.fetchData();
          this.$message.success("公告删除成功");
        })
        .catch((error) => {
          console.error("Error deleting notice:", error);
          this.$message.error("删除公告时出错");
        });
    },
    handleDetail(row) {
      this.selectedNotice = row;
      this.detailDialogVisible = true; // 打开显示具体信息的弹出窗口
    },
    handleEdit(index, row) {
      this.isAdd = false;
      this.selectedNotice = { ...row }; // 克隆选中的公告数据以避免直接修改原始数据
      this.editDialogVisible = true; // 打开编辑表单
    },
    handleDelete(index, row) {
      let id = row.id;
      this.$confirm("确定要删除这条公告吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击了确定按钮，调用deleteNotice方法
          this.deleteNotice(id);
        })
        .catch(() => {
          // 用户点击了取消按钮，不做任何操作
        });
    },
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage;
      // 在此刷新数据
      this.fetchData();
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      // 在此刷新数据
      this.fetchData();
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    fetchNotices() {
      this.$http
        .get("/notifications/all")
        .then((response) => {
          // 后端返回的数据直接是公告数组
          this.notices = response.data.map((notice) => ({
            id: notice.notiId,
            title: notice.notiTitle,
            date: this.formatDate(new Date(notice.notiTimestamp)), // 注意这里可能需要格式化日期
            content: notice.notiContent,
            sender: notice.notiSender,
          }));
        })
        .catch((error) => {
          console.error("Error fetching notices:", error);
        });
    },
  },
};
</script>
<style scoped>
.outbox {
  margin: 20px;
}
h2 {
  display: flex;
  justify-content: space-between;
}
.pagination {
  margin-top: 30px;
  text-align: center;
}

/* 修改p标签内文本的样式 */
p {
  margin: 10px 0; /* 修改段落之间的垂直间距 */
  font-size: 16px; /* 修改文本字体大小 */
}

/* 修改strong标签内文本的样式 */
strong {
  font-weight: bold; /* 设置文本为粗体 */
}
</style>